//创建用户相关的小仓库
import { defineStore } from 'pinia'
// @ts-ignore
import { GET_TOKEN, SET_USER, GET_USERFION, SET_TOKEN, DELE_TOEKN, DELE_USER } from '@/utils/token'
//引入api
import { login, upinfo, getuseinfo, upavatar, forgetpass } from '@/api/user.ts'


import { ElMessage, ElNotification } from 'element-plus';
//创建小仓库
const userUserRouter = defineStore('User', {
    //纯数据的地方
    state: () => {
        return {
            token: GET_TOKEN(),
            userinfo: JSON.parse(GET_USERFION() as string) ? JSON.parse(GET_USERFION() as string) : {}
        }
    },
    //异步方法
    actions: {

        //传入用户登录信息
        async userlogin(data: any) {
            const result: any = await login(data)
            // if(result.code==200)
            console.log(result, '结果')
            console.log(result.code, '？？')
            if (result.code == 200) {
                this.token = result.token
                SET_TOKEN(result.token)
                SET_USER(result.data[0])
                console.log(JSON.parse(GET_USERFION() as string))
                this.userinfo = result.data[0]
                ElNotification({
                    type: 'success',
                    message: '登录成功',
                    title: `登录成功`
                })

            } else {

            }
        },
        //用户修改信息
        async upinfos(data: any, id: any) {
            let result: any = await upinfo(data, id)
            if (result.code == 200) {
                this.getuserinfo(id)
            }
        },
        async getuserinfo(id: any) {
            let result: any = await getuseinfo(id)
            console.log('查询', result)
            if (result.code == 200) {
                SET_USER(result.data)
            }
        },
        //修改头像
        async upavatar(data: any) {
            let result: any = await upavatar(data)
            if (result.code == 200) {
                this.getuserinfo(data.id)
            }
        },
        //忘记密码
        async forgetpass(data: any) {
            let result: any = await forgetpass(data)
            if (result.code == 200) {
                ElMessage({
                    message: '修改成功',
                    type: 'success'
                })
            } else {

            }
        },
        //退出登录
        async logout() {
            this.token = ''
            this.userinfo = {}
            DELE_TOEKN()
            DELE_USER()
        }
    }


})

export default userUserRouter